package com.itheima.reggie.web.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class loginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("登录过滤器......");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的URI
        String url = request.getRequestURI();
        //定义不需要处理的请求路径
        String urls[] = {
                "/employee/login",
                "/employee/logout",
                "/backend",
                "/front"
        };
        for (String path : urls) {
            if (url.contains(path)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
       /*   //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }*/
        //2.判断用户是否登录（session）
        HttpSession session = request.getSession();
        Object emp = session.getAttribute("emp");
        if (emp != null) {
            //登录了
            //用户有访问权限，将用户的id存储到当前线程的threadlocal，
            BaseContext.setCurrentId((Long) emp);
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }


        // 3.资源不直接放行，用户未登录，访问失败，（前端）跳转到登录页面
         servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));



    }
}
